const db = uniCloud.database();
const dbcmd = db.command;
module.exports = {
	_before: function() { // 通用预处理器
	},
	/**更新数据库music信息
	 * @param {object} musicInfo - 音频信息
	 * @param {string} musicInfo._id - 数据库ID
	 * @param {string} musicInfo.name - 音频名字
	 * @param {string} musicInfo.cloudFilePath - 云存储路径
	 * @returns {object} 返回值描述
	 */
	async AddMsic(musicInfo) {
		try {
			// 判断item里面是否包含name和cloudFilePath属性
			if (!('name' in musicInfo && musicInfo.name !== 'undefined')) {
				throw new Error('没有name属性');
			} else if (!('cloudFilePath' in musicInfo && musicInfo.cloudFilePath !== 'undefined')) {
				throw new Error('没有cloudFilePath属性');
			}
			let res = await db.collection('musicList').add({
				name: musicInfo.name,
				cloudFilePath: musicInfo.cloudFilePath,
				upLoadTime: new Date().getTime(),
			});
			return res;
		} catch (err) {
			console.log(err);
			return '错误';
		}
	},
	/**获取数据库所有歌曲列表
	 * 
	 */
	async getMusicList() {
		return await db.collection('musicList').get();
	},
	/**获取数据库music信息
	 * 
	 * @param {string} musicID - 歌曲信息
	 * @return {Object}
	 */
	async getMusicInfo(musicID) {
		return await db.collection('musicList').where({
			_id: musicID
		}).get();
	},
	/**删除云存储music文件 和 数据库music信息
	 * 
	 * @param {object[]} musicInfos - 音频信息
	 * @param {string} musicInfos[]._id - 歌曲数据库ID
	 * @param {string} musicInfos[].cloudFilePath - 歌曲云存储路径
	 * @returns {object}
	 * @property {number} res.code
	 * @property {string} res.message
	 */
	async deleteMusic(musicInfos) {
		try {
			// 删除云存储文件
			let fileList = [];
			let musicIDs = [];
			if (Array.isArray(musicInfos)) {
				fileList = musicInfos.map(item => item.cloudFilePath);
				musicIDs = musicInfos.map(item => item._id);
			} else {
				fileList.push(musicInfos.cloudFilePath);
				musicIDs.push(musicInfos._id);
			}
			const res = await uniCloud.deleteFile({
				fileList: fileList
			});

			//删除云数据库记录
			let p = []
			musicIDs.forEach((item, index) => {
				p[index] = new Promise((resolve, reject) => {
					db.collection('musicList').where({
						_id: item
					}).remove().then(res => {
						resolve(res);
					});
				});
			});

			Promise.all(p).then(res => {
				console.log(res);
			});

			return {
				code: 0,
				message: '文件删除成功',
				data: res
			};
		} catch (error) {
			return {
				code: 1,
				message: '文件删除失败',
				error: error.message
			};
		}
	},
	/**搜索音乐信息
	 * @param {Object} musicInfo
	 */
	async searchMusic(musicInfo) {
		let {
			name
		} = musicInfo;
		res = await db.collection('musicList').where({
			name: new RegExp(name),
		}).get();
		return {
			success: "success",
			message: '音乐搜索成功',
			data: res
		};

	},
	/** 通过id数组所有歌曲信息
	 * 
	 */
	async Get_all_musicInfo_by_idList(idList) {
		res = await db.collection('musicList').where({
			_id:dbcmd.in(idList),
		}).get();

		return {
			success: "success",
			message: '获取歌曲信息列表成功',
			data: res.data
		};
	}
}